// 初始化canvas
import { fabric } from "fabric";
import { initAligningGuidelines } from "@/utils/aligning_guidelines_plus_ultimate.js"; // 引入辅助线方法
export function initCanvas(vm) {
  return {
    // 重置数据
    canvasrResetData() {
      window.location.reload();
    },
    // 初始化画布
    async canvasInitImageEffectCanvas(result1, result2, result3, result7) {
      let that = vm;
      if (result1 && result2 && result3 && result7) {
        vm.canvas = new fabric.Canvas("imageEffectCanvas", {
          width: that.canvasWidth,
          height: that.canvasHeight,
          backgroundColor: "#dddddd",
          selection: false,
          hoverCursor: "default",
          renderOnAddRemove: false, // 添加/移除对象时不自动渲染
          skipOffscreen: true, // 跳过屏幕外的对象
          preserveObjectStacking: true, // 保持对象堆叠顺序
          imageSmoothingEnabled: true, // 启用图像平滑
        });
        // 添加底图
        const flage = await vm.canvasAddBackgroundImage();
        // // 添加坐标轴
        vm.canvasAddAxes(flage);
        // 事件监听
        vm.canvas
          .on("mouse:down", vm.handleCanvasMouseDown)
          .on("mouse:move", vm.handleMouseMove)
          .on("mouse:up", vm.handleMouseUp)
          .on("mouse:wheel", vm.handleMouseWheel)
          .on("object:modified", vm.handleObjectModified)
          .on("selection:created", vm.handleObjectSelected)
          .on("selection:updated", vm.handleObjectSelected)
          .on("selection:cleared", vm.handleObjectDeselected)
          .on("object:moving", vm.handleObjectMoving)
          .on("object:rotating", vm.handleObjectMoving)
        // .on('after:render', () => {
        //   vm.canvasAddruler()
        // })
        // 监听键盘事件
        document.addEventListener("keydown", vm.handleKeyDown);
        // 启用辅助线
        initAligningGuidelines(vm.canvas);
        // vm.canvas.requestRenderAll(); // 强制刷新画布
        // vm.throttledRender();
        if (flage && flage.length > 0) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    canvasRemoveEventListeners() {
      vm.canvas
        .off("mouse:down", vm.handleCanvasMouseDown)
        .off("mouse:move", vm.handleMouseMove)
        .off("mouse:up", vm.handleMouseUp)
        .off("mouse:wheel", vm.handleMouseWheel)
        .off("object:modified", vm.handleObjectModified)
        .off("selection:created", vm.handleObjectSelected)
        .off("selection:updated", vm.handleObjectSelected)
        .off("selection:cleared", vm.handleObjectDeselected)
        .off("object:moving", vm.handleObjectMovement)
        .off("object:rotating", vm.handleObjectMovement)
      // .off('after:render', () => {
      //   vm.canvasAddruler()
      // })
      document.removeEventListener("keydown", vm.handleKeyDown);
    },
    // 初始化点位信息（反显已有数据）
    async canvasInitPositionInfo(floorPoint) {
      let result;
      // 若楼层点位信息不为空，则绘制楼层的详细点位信息
      if (floorPoint.length > 0) {
        let num = 0;
        for (const [index, item] of floorPoint.entries()) {
          // 根据item的model去对应的模型列表imgArr中找到对应的模型对象
          const model = vm.imgArr.find((img) => {
            return img.modelId == item.model;
          });
          if (model) {
            try {
              // 加载图片
              const imgObj = await vm.wayLoadImage(model.imageUrl);
              // 获取图片的原始宽度和高度
              const originalWidth = model.w;
              const originalHeight = model.h;
              // 计算图片的显示宽度和高度，基于原始尺寸和一个固定的比例
              // const displayWidth = originalWidth * vm.rate;
              // const displayHeight = originalHeight * vm.rate;
              const displayWidth = item.w; // 使用存储的宽度
              const displayHeight = item.h; // 使用存储的高度
              const scaleX = displayWidth / originalWidth;
              const scaleY = displayHeight / originalHeight;
              // 创建Fabric图像对象
              const fabricImg = vm.constructionFabricImage(
                imgObj,
                item.x,
                item.y,
                scaleX,
                scaleY,
                item.r,
                model.modelId,
                model.imageUrl
              );
              // 添加对象到画布
              vm.canvas.add(fabricImg);
              // fabricImg.moveTo(3);
              // 始终创建箭头对象，但根据isArrowVisible设置其可见性
              const arrow = vm.wayArrowAdd(item.x, item.y, displayHeight);
              arrow.visible = vm.isArrowVisible;
              // 创建边框对象
              const border = vm.wayBorderAdd(
                item.x,
                item.y,
                displayWidth,
                displayHeight,
                item.r
              );
              border.visible = vm.isBorderVisible;
              // 生成文字
              const text = vm.wayTextAdd(
                item.x,
                item.y,
                "selectedImg",
                item?.posName ?? "未知名称"
              );
              text.visible = vm.isTextVisible;
              text.angle = item.r; // 设置文字的角度与图片一致
              // 更新箭头的位置和角度
              vm.arrowcompute(
                { fabricObject: fabricImg, arrowObject: arrow },
                displayHeight,
                item.x,
                item.y,
                item.r
              );
              // 将config转成对象
              let configForm;
              const configvalue = item?.config ?? "";
              if (configvalue.length > 0) {
                configForm = JSON.parse(configvalue);
              } else {
                configForm = {};
              }
              // 保存到 allObjects
              vm.allObjects.push({
                allObjectsid: Date.now(),
                text: item?.posName ?? "未知名称",
                x: item.x,
                y: item.y,
                width: displayWidth,
                height: displayHeight,
                angle: item.r,
                fabricObject: fabricImg,
                textObject: text,
                arrowObject: arrow,
                borderObject: border,
                imgtarget: model,
                pointObject: item,
                posNo: item.posNo
                  ? item.posNo
                  : Math.floor(Date.now() / 1000) + "", // 初始化 posNo
                posId: item.posId,
                type: item.type,
                configForm: configForm,
                configFormOld: configForm, // 承接原有配置
                tags: item?.tags ?? [],
              });
              // console.log("vm.allObjects", vm.allObjects);
              num++;
            } catch (error) {
              result = false;
            }
          } else {
            result = false;
          }
        }
        if (num == floorPoint.length) {
          result = true;
        } else {
          result = false;
        }
      } else {
        result = true;
      }
      // 更新所有对象坐标
      vm.updateAllObjectsCoords();
      return result;
    },
    // 画布重新渲染
    canvasRender(result4) {
      return new Promise((resolve) => {
        const render = () => {
          if (result4) {
            vm.canvas.requestRenderAll();
            // vm.throttledRender();
            setTimeout(() => {
              vm.mapLoading = false;
            }, 200);
            resolve(true);
          } else {
            requestAnimationFrame(render);
          }
        };
        requestAnimationFrame(render);
      });
    },
    // 初始化视图，确保底图居中并适应画布
    canvasInitializeView() {
      if (!vm.backgroundImage) return;
      const canvasWidth = vm.canvas.width;
      const canvasHeight = vm.canvas.height;
      const imgWidth = vm.backgroundImage.width;
      const imgHeight = vm.backgroundImage.height;
      const scaleX = canvasWidth / imgWidth;
      const scaleY = canvasHeight / imgHeight;
      const initialZoom = Math.min(scaleX, scaleY);
      vm.initialZoom = initialZoom; // 保存初始缩放比例
      const translateX = (canvasWidth - imgWidth * initialZoom) / 2;
      const translateY = (canvasHeight - imgHeight * initialZoom) / 2;
      vm.canvas.setViewportTransform([
        initialZoom,
        0,
        0,
        initialZoom,
        translateX,
        translateY,
      ]);
      vm.canvas.requestRenderAll(); // 强制刷新画布
      // vm.throttledRender();
    },
    // 添加底图
    async canvasAddBackgroundImage() {
      const imageUrl = vm.backimg;
      const imgObj = await vm.wayLoadImage(imageUrl);
      const originalWidth = imgObj.width;
      const originalHeight = imgObj.height;
      // console.log(originalWidth, originalHeight);
      // vm.originalBackgroundWidth = originalWidth; // 保存底图的原始宽度
      // vm.originalBackgroundHeight = originalHeight; // 保存底图的原始高度
      fabric.Image.fromURL(imageUrl, (img) => {
        img.set({
          left: 0,
          top: 0,
          selectable: false, // 底图不可选中
          evented: false, // 底图不可交互
          lockMovementX: true, // 底图禁止水平移动
          lockMovementY: true, // 底图禁止垂直移动
        });
        vm.canvas.add(img);
        vm.backgroundImage = img;
        vm.canvasInitializeView();
      });
      if (imgObj) {
        return [originalWidth, originalHeight];
      }
    },
    canvasAddAxes(flage) {
      const xAxis = new fabric.Line([0, 0, flage[0], 0], {
        stroke: "#F56C6C",
        strokeWidth: 4,
        selectable: false,
        evented: false
      });
      const yAxis = new fabric.Line([0, 0, 0, flage[1]], {
        stroke: "#F56C6C",
        strokeWidth: 4,
        selectable: false,
        evented: false
      });
      vm.canvas.add(xAxis, yAxis);
      // vm.canvas.requestRenderAll(); // 强制刷新画布
    },
    // todo 添加标尺
    // canvasAddruler() {
    //   const canvas = vm.canvas;
    //   const rulerMargin = 20; // 标尺与画布边缘的间距
    //   const tickSpacing = 50; // 刻度间距
    //   const smallTickHeight = 5; // 小刻度高度
    //   const largeTickHeight = 10; // 大刻度高度
    //   const smallTickWidth = 5; // 小刻度宽度
    //   const largeTickWidth = 10; // 大刻度宽度
    //   const fontSize = 10; // 刻度文字大小
    //   console.log(canvas.getWidth(), canvas.getHeight())
    //   // 绘制水平标尺
    //   const horizontalRuler = new fabric.Rect({
    //     left: 0,
    //     top: 0,
    //     width: canvas.getWidth(),
    //     height: rulerMargin,
    //     fill: 'rgba(200, 200, 200, 0.5)',
    //     selectable: false,
    //     evented: false
    //   });
    //   canvas.add(horizontalRuler);

    //   // 绘制垂直标尺
    //   const verticalRuler = new fabric.Rect({
    //     left: 0,
    //     top: 0,
    //     width: rulerMargin,
    //     height: canvas.getHeight(),
    //     fill: 'rgba(200, 200, 200, 0.5)',
    //     selectable: false,
    //     evented: false
    //   });
    //   canvas.add(verticalRuler);

    //   // 绘制水平标尺刻度
    //   for (let x = 0; x < canvas.getWidth(); x += tickSpacing) {
    //     const tickHeight = x % (tickSpacing * 5) === 0 ? largeTickHeight : smallTickHeight;
    //     const tick = new fabric.Line([x, 0, x, tickHeight], {
    //       stroke: 'black',
    //       selectable: false,
    //       evented: false
    //     });
    //     canvas.add(tick);

    //     if (x % (tickSpacing * 5) === 0) {
    //       const text = new fabric.Text(x.toString(), {
    //         left: x + 2,
    //         top: tickHeight + 2,
    //         fontSize: fontSize,
    //         fill: 'black',
    //         selectable: false,
    //         evented: false
    //       });
    //       canvas.add(text);
    //     }
    //   }

    //   // 绘制垂直标尺刻度
    //   for (let y = 0; y < canvas.getHeight(); y += tickSpacing) {
    //     const tickWidth = y % (tickSpacing * 5) === 0 ? largeTickWidth : smallTickWidth;
    //     const tick = new fabric.Line([0, y, tickWidth, y], {
    //       stroke: 'black',
    //       selectable: false,
    //       evented: false
    //     });
    //     canvas.add(tick);

    //     if (y % (tickSpacing * 5) === 0) {
    //       const text = new fabric.Text(y.toString(), {
    //         left: tickWidth + 2,
    //         top: y - fontSize / 2,
    //         fontSize: fontSize,
    //         fill: 'black',
    //         selectable: false,
    //         evented: false
    //       });
    //       canvas.add(text);
    //     }
    //   }

    //   // 监听画布缩放和滚动事件，更新标尺
    //   canvas.on('object:modified', () => {
    //     // 这里可以添加更新标尺的逻辑
    //     // 例如：重新计算刻度位置和文字内容
    //   });
    // },
  }
}
